namespace Trader.BO
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Interface;

    public class QuotesCollection : IQuotesCollection
    {
        private static readonly TimeSpan oneDay = TimeSpan.FromDays(1);
        private readonly IDictionary<DateTime, IQuote> quotesDictionary;
        private DateTime? min;

        public QuotesCollection()
        {
            quotesDictionary = new Dictionary<DateTime, IQuote>();
        }

        #region IQuotesCollection Members

        public IQuote this[DateTime date]
        {
            get
            {
                IQuote quote;
                if (!quotesDictionary.TryGetValue(date, out quote))
                {
                    if (quotesDictionary.Count == 0 || date < min.Value)
                    {
                        return null;
                    }

                    DateTime searchDate = date - oneDay;
                    while (!TryGetValue(searchDate, out quote))
                    {
                        searchDate -= oneDay;
                    }
                }

                return quote;
            }
        }

        public void Add(DateTime date, IQuote quote)
        {
            quotesDictionary.Add(date, quote);
            if (min == null || date < min)
            {
                min = date;
            }
        }

        public bool ContainsKey(DateTime date)
        {
            return quotesDictionary.ContainsKey(date);
        }

        public bool TryGetValue(DateTime date, out IQuote quote)
        {
            return quotesDictionary.TryGetValue(date, out quote);
        }

        public IEnumerator<KeyValuePair<DateTime, IQuote>> GetEnumerator()
        {
            return quotesDictionary.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}